﻿using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Linq;
using QJY.API;
using QJY.Common;
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Web;

namespace LotusBIWeb
{
    /// <summary>
    /// VIEWAPI 的摘要说明
    /// </summary>
    public class VIEWAPI : IHttpHandler
    {
        public string ComId { get; set; }

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            context.Response.AddHeader("Access-Control-Allow-Origin", "*");
            context.Response.AddHeader("Access-Control-Allow-Methods", "POST,GET,OPTIONS,DELETE"); //支持的http 动作
            context.Response.AddHeader("Access-Control-Allow-Headers", "Accept, Origin, Content-type,authorization");
            context.Response.AddHeader("Access-Control-Allow-Credentials", "true");
            context.Response.AddHeader("pragma", "no-cache");
            context.Response.AddHeader("cache-control", "");
            context.Response.CacheControl = "no-cache";
            string strAction = context.Request["Action"] ?? "";
            string UserName = "";
            string wxopenid = context.Request["wxopenid"] ?? "";
            string szhlcode = context.Request["szhlcode"] ?? "";

            szhlcode = szhlcode.Replace(' ', '+');
            string strIP = getIP(context);//用户IP
            Msg_Result Model = new Msg_Result() { Action = strAction.ToUpper(), ErrorMsg = "" };
            if (!string.IsNullOrEmpty(strAction))
            {

                string strCheckString = "";// new CommonHelp().checkconetst(context);
                if (strCheckString != "")
                {
                    Model.ErrorMsg = strAction + "有敏感字符串";
                    new JH_Auth_LogB().InsertLog(strAction, Model.ErrorMsg, strCheckString, UserName, "", 0, strIP);
                }
                else
                {
                    Model.ErrorMsg = "";
                    if (strAction == "UPFILE")
                    {
                        try
                        {
                            List<string> filePathResultList = new List<string>();
                            for (int i = 0; i < context.Request.Files.Count; i++)
                            {
                                HttpPostedFile uploadFile = context.Request.Files[i];

                                string originalName = uploadFile.FileName;
                                string[] temp = uploadFile.FileName.Split('.');

                                string filename = System.Guid.NewGuid() + "." + temp[temp.Length - 1].ToLower();
                                uploadFile.SaveAs(HttpContext.Current.Request.MapPath("~/upload/" + filename));
                                filePathResultList.Add("/upload/" + filename);

                            }
                            Model.Result = filePathResultList;

                        }
                        catch (Exception ex)
                        {
                            Model.ErrorMsg = strAction + "接口调用失败,请检查日志";
                            Model.Result = ex.ToString();
                            new JH_Auth_LogB().InsertLog("错误日志", context.Request.Path + "/" + strAction, Model.ErrorMsg, "", "错误用户", 0, strIP);

                        }

                    }
                    else if (strAction == "UPDCMB")
                    {
                        var files = context.Request.Files;
                        int size = files[0].ContentLength;

                        if (size > 10485760)
                        {
                            Model.ErrorMsg = "大小不能超过10M";
                        }

                        List<string> filePathResultList = new List<string>();
                        for (int i = 0; i < context.Request.Files.Count; i++)
                        {


                            HttpPostedFile uploadFile = context.Request.Files[i];

                            string originalName = uploadFile.FileName;
                            string[] temp = uploadFile.FileName.Split('.');
                            if (!originalName.Contains(".doc"))
                            {
                                Model.ErrorMsg = "只能上传.doc格式";
                            }
                            string filename = System.Guid.NewGuid() + "." + temp[temp.Length - 1].ToLower();
                            uploadFile.SaveAs(HttpContext.Current.Request.MapPath("~/upload/dcmb/" + filename));
                            filePathResultList.Add("/upload/dcmb/" + filename);

                        }
                        Model.Result = filePathResultList;
                    }
                    else if (strAction == "UPLOG")
                    {
                        var files = context.Request.Files;
                        int size = files[0].ContentLength;

                        if (size > 10485760)
                        {
                            Model.ErrorMsg = "大小不能超过10M";
                        }

                        List<string> filePathResultList = new List<string>();
                        for (int i = 0; i < context.Request.Files.Count; i++)
                        {


                            HttpPostedFile uploadFile = context.Request.Files[i];

                            string originalName = uploadFile.FileName;
                            string[] temp = uploadFile.FileName.Split('.');
                            if (!originalName.Contains(".doc"))
                            {
                                Model.ErrorMsg = "只能上传.doc格式";
                            }
                            string filename = "QYLog." + temp[temp.Length - 1].ToLower();
                            uploadFile.SaveAs(HttpContext.Current.Request.MapPath("~/upload/log/" + filename));
                            filePathResultList.Add("/upload/log/" + filename);

                        }
                        Model.Result = filePathResultList;
                    }
                    else if (strAction == "UPEXCEL")
                    {
                        //上传读取Excel
                        var file = context.Request.Files[0];
                        string headrow = context.Request.Form["headrow"].ToString();
                        string suffix = file.FileName.Split('.')[1];
                        Model.Result = new CommonHelp().ExcelToTable(file.InputStream, int.Parse(headrow), suffix);
                    }
                    else if (strAction.StartsWith("PUB_"))
                    {
                        try
                        {
                            StreamReader sr = new StreamReader(HttpContext.Current.Request.InputStream);
                            string responseStr = sr.ReadToEnd();
                            JObject JsonData = new JObject();
                            if (!string.IsNullOrEmpty(responseStr))
                            {
                                JsonData = JObject.Parse(responseStr);

                            }
                            string P1 = JsonData["P1"] == null ? "" : JsonData["P1"].ToString();
                            string P2 = JsonData["P2"] == null ? "" : JsonData["P2"].ToString();


                            foreach (var item in context.Request.Cookies.AllKeys)
                            {
                                if (!JsonData.ContainsKey(item))
                                {
                                    JsonData.Add(item, context.Request.Cookies[item].Value);
                                }
                            }
                            foreach (var item in context.Request.QueryString.AllKeys)
                            {
                                if (!JsonData.ContainsKey(item))
                                {
                                    JsonData.Add(item, context.Request.QueryString[item]);
                                }
                            }
                            var function = Activator.CreateInstance(typeof(PubManage)) as PubManage;
                            var method = function.GetType().GetMethod(strAction.Split('_')[1].ToUpper());
                            method.Invoke(function, new object[] { JsonData, Model, P1, P2, null });
                        }
                        catch (Exception ex)
                        {
                            Model.ErrorMsg = strAction + "接口调用失败,请检查日志";
                            Model.Result = ex.ToString();
                            // new JH_Auth_LogB().InsertLog(Action, Model.ErrorMsg + ex.StackTrace.ToString(), ex.ToString(), "", "", 0, "");
                        }
                    }
                    else
                    {
                        #region 必须登录执行接口

                        var acs = Model.Action.Split('_');

                        if (szhlcode != "")
                        {

                            TokenJWT jwt = JwtHelper.DePJWT(szhlcode);

                            string strUserName = jwt.UserName;
                            long dtexp = long.Parse(jwt.Exp);
                            if (DateTime.Now.AddMinutes(5).ToUniversalTime().Ticks > dtexp)
                            {
                                //需要更新Token
                                Model.uptoken = JwtHelper.CreateJWT(strUserName).Token;
                            }
                            JH_Auth_UserB.UserInfo UserInfo = CacheHelp.Get(strUserName) as JH_Auth_UserB.UserInfo;
                            if (UserInfo == null)
                            {
                                UserInfo = new JH_Auth_UserB().GetUserInfo(10334, strUserName);
                                CacheHelp.Set(strUserName, UserInfo);
                            }
                            try
                            {

                                StreamReader sr = new StreamReader(HttpContext.Current.Request.InputStream);
                                string responseStr = sr.ReadToEnd();
                                JObject JsonData = new JObject();
                                if (!string.IsNullOrEmpty(responseStr))
                                {
                                    JsonData = JObject.Parse(responseStr);

                                }
                                string P1 = JsonData["P1"] == null ? "" : JsonData["P1"].ToString();
                                string P2 = JsonData["P2"] == null ? "" : JsonData["P2"].ToString();


                                foreach (var item in context.Request.Cookies.AllKeys)
                                {
                                    if (!JsonData.ContainsKey(item))
                                    {
                                        JsonData.Add(item, context.Request.Cookies[item].Value);
                                    }
                                }

                                Type type = Assembly.Load("QJY.API").GetType("QJY.API." + strAction.Split('_')[0] + "Manage");
                                //2.GetMethod(需要调用的方法名称)
                                MethodInfo method = type.GetMethod(strAction.Split('_')[1].ToUpper());
                                // 3.调用的实例化方法（非静态方法）需要创建类型的一个实例
                                object obj = Activator.CreateInstance(type);
                                //4.方法需要传入的参数
                                if (strAction.Split('_')[0] == "FILE")
                                {
                                    object[] parameters = new object[] { JsonData, Model, P1, P2, UserInfo, context };
                                    method.Invoke(obj, parameters);

                                }
                                else
                                {
                                    object[] parameters = new object[] { JsonData, Model, P1, P2, UserInfo };
                                    method.Invoke(obj, parameters);

                                }


                                new JH_Auth_LogB().InsertLog("系统日志", context.Request.Path + "/" + Model.Action, JsonConvert.SerializeObject(Model), UserInfo.User.UserName, JsonConvert.SerializeObject(JsonData), UserInfo.QYinfo.ComId, strIP);
                            }
                            catch (Exception ex)
                            {
                                Model.ErrorMsg = "接口调用失败,请检查日志" + ex.StackTrace.ToString();
                                Model.Result = ex.ToString();
                                new JH_Auth_LogB().InsertLog("错误日志", context.Request.Path + "/" + strAction, Model.ErrorMsg, "", "错误用户", 0, strIP);

                            }
                        }
                        else
                        {
                            Model.ErrorMsg = "NOSESSIONCODE3";
                        }
                        #endregion
                    }

                }



            }
            string jsonpcallback = context.Request["jsonpcallback"] ?? "";
            IsoDateTimeConverter timeConverter = new IsoDateTimeConverter();
            timeConverter.DateTimeFormat = "yyyy-MM-dd HH:mm:ss";
            string Result = JsonConvert.SerializeObject(Model, Formatting.Indented, timeConverter).Replace("null", "\"\"");
            if (jsonpcallback != "")
            {
                Result = jsonpcallback + "(" + Result + ")";//支持跨域
            }
            context.Response.Write(Result);
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }


        public string getIP(HttpContext context)
        {
            string ipAddr = "";
            try
            {
                HttpRequest Request = context.Request;
                // 如果使用代理，获取真实IP  
                if (Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != "")
                    ipAddr = Request.ServerVariables["REMOTE_ADDR"];
                else
                    ipAddr = Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
                if (ipAddr == null || ipAddr == "")
                    ipAddr = Request.UserHostAddress;
                return ipAddr;

            }
            catch (Exception ex)
            {
                return "";
            }
            return ipAddr;
        }
    }


    public class UserCatche
    {
        public DateTime CatcheTime { get; set; }
        public JH_Auth_UserB.UserInfo User { get; set; }


    }
}